package general

import (
	"alex/ptp1588boundaryclock/datasets"
	"alex/ptp1588boundaryclock/datatypes"
)

type Delay_RespMessage struct {
	ParentDS *datasets.ParentDS
	Timestamp *datatypes.TimeStamp
}

func (a* Delay_RespMessage) Init() {
	a.ParentDS = new(datasets.ParentDS)
	a.Timestamp = new(datatypes.TimeStamp)
}

// =====================================================================================================================
// Write Delay_Resp Message
// =====================================================================================================================

// Writes the Delay_Resp Message
func (a *Delay_RespMessage) Write(delay_resp []byte, done chan bool) {
	// 13.8.2.1 receiveTimestamp (Timestamp)
	// 9.5.12 The receiveTimestamp field of the Delay_Resp shall be the <delayReqEventIngressTimestamp> of the associated Delay_Req message.
	for i := 0; i < 10; i++ {
		delay_resp[i] = 0
	}
	// 13.8.2.2 requestingPortIdentity (PortIdentity)
	// 11.3.2 Copy the sourcePortIdentity field from the Delay_Req message to the requestingPortIdentity field of the Delay_Resp message
	for key, value := range a.ParentDS.ParentPortIdentity.ClockIdentity {
		delay_resp[key] = value
	}
	done <- true
}

// =====================================================================================================================
// Read Delay_Resp Message
// =====================================================================================================================

// Reads, checks and sets the Delay_Resp Message values
func (a* Delay_RespMessage) Read(delay_resp []byte) (check bool) {
	check = true
	// originTimestamp 13.5.2.1
	a.readReceiveTimestamp(delay_resp[:10])
	// 13.8.2.2 requestingPortIdentity (PortIdentity)
	for key, value := range delay_resp {
		a.ParentDS.ParentPortIdentity.ClockIdentity[key] = value
	}
	return
}

// Reads and sets the originTimestamp 13.5.2.1
func (a* Delay_RespMessage) readReceiveTimestamp(timestamp []byte) {
	// we use uint64 since uint48 is not available in Go
	a.Timestamp.SecondsField = uint64(timestamp[0]) << 40 | uint64(timestamp[1]) << 32 | uint64(timestamp[2]) <<
			24 | uint64(timestamp[3]) << 16 | uint64(timestamp[4]) << 8 | uint64(timestamp[5])
	a.Timestamp.NanosecondsField = uint32(timestamp[6]) << 24 | uint32(timestamp[7]) << 16 | uint32(timestamp[8]) <<
			8 | uint32(timestamp[9])
}
